package com.jnu.myaccount;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.inputmethodservice.KeyboardView;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.text.InputType;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jnu.myaccount.data.DataBank;
import com.jnu.myaccount.data.Money;
import com.jnu.myaccount.ui.CostItem;

import java.security.PrivateKey;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link AccountFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class AccountFragment extends Fragment {
    //CostItemList用于存储数据
    private List<CostItem> costItemList =new ArrayList<>();
    private GridView costGridView;
    private TextView moneyName;
    private EditText moneyNumber;
    private TextView moneyDate;
    private TextView moneyIncome;
    private TextView moneySpend;
    private int moneyYear;
    private int moneyMonth;
    private int moneyDay;
    private Double moneyNum;
    private String moneyContent;
    private int moneyId;
    private int position;
    private boolean income;

    // 定义用来与外部activity交互，获取到宿主activity
    private FragmentInteraction listTerNer;

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        if(context instanceof FragmentInteraction) {
            listTerNer = (FragmentInteraction)context; // 获取到宿主activity并赋值
        } else{
            throw new IllegalArgumentException("activity must implements FragmentInteraction");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        listTerNer=null;
    }

    public AccountFragment() {
        // Required empty public constructor
    }

    public static AccountFragment newInstance() {
        AccountFragment fragment = new AccountFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
        }
        //先拿到数据并初始化在适配器上
        initItems();        //初始化costItemList的数据

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView=inflater.inflate(R.layout.fragment_acount,container,false);

        //初始化
        moneyId=costItemList.get(0).getItem_id();
        moneyYear=0;
        position=-1;
        income=true;
        
        //将适配器上的数据传给costItemList
        costGridView =(GridView) rootView.findViewById(R.id.my_grid_view);
        CostItemAdapter costItemAdapter=new CostItemAdapter(AccountFragment.this.getContext(),R.layout.grid_view_item,costItemList);
        costGridView.setAdapter(costItemAdapter);
        
        //初始化各控件
        moneyName=(TextView)rootView.findViewById(R.id.cost_name); 
        moneyNumber=(EditText)rootView.findViewById(R.id.editMoney);
        moneyNumber.setHint("0.00");
        moneyNum=0.00;
        moneyDate=(TextView)rootView.findViewById(R.id.date);
        moneyIncome=(TextView)rootView.findViewById(R.id.money_income);
        moneySpend=(TextView)rootView.findViewById(R.id.money_spend);
        moneyIncome.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                income=true;
                moneyIncome.setBackgroundColor(Color.parseColor("#00ff00"));
                moneySpend.setBackgroundColor(Color.parseColor("#33ccff"));
            }
        });
        moneySpend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                income=false;
                moneySpend.setBackgroundColor(Color.parseColor("#00ff00"));
                moneyIncome.setBackgroundColor(Color.parseColor("#33ccff"));
            }
        });

        Intent intent=getActivity().getIntent();
        String name=intent.getStringExtra("name");
        if(name!=null&&name.equals("edit")){
            Bundle bundle=intent.getExtras();
            position=bundle.getInt("position");
            moneyId=bundle.getInt("editId");
            moneyYear=bundle.getInt("Year");
            moneyMonth= bundle.getInt("Month");
            moneyDay= bundle.getInt("Day");
            moneyNum=bundle.getDouble("editNumber");
            moneyContent=bundle.getString("editName");
            moneyName.setText(moneyContent);
            int month=moneyMonth+1;
            moneyDate.setText(bundle.getInt("Year")+"-"+month+"-"+bundle.getInt("Day"));
            moneyNumber.setHint(String.valueOf(moneyNum));
        }

        costGridView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                moneyId=costItemList.get(position).getItem_id();
                moneyContent=costItemList.get(position).getItem_name();
                moneyName.setText(costItemList.get(position).getItem_name());
            }
        });

        final DatePicker[] datePicker = new DatePicker[1];
        final int[] year = {0};
        final int[] month = new int[1];
        final int[] dayOfMonth = new int[1];
        //点击"日期"按钮布局 设置日期
        moneyDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //通过自定义控件AlertDialog实现
                AlertDialog.Builder builder = new AlertDialog.Builder(AccountFragment.this.getContext());
                View view = (LinearLayout) getLayoutInflater().inflate(R.layout.date_layout, null);
                datePicker[0] = (DatePicker) view.findViewById(R.id.date_picker);
                //设置日期简略显示 否则详细显示 包括:星期\周
                datePicker[0].setCalendarViewShown(false);
                //设置date布局
                builder.setView(view);
                builder.setTitle("选择日期");
                builder.setPositiveButton("确 定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //日期格式
//                        year[0] = datePicker[0].getYear();
//                        month[0] = datePicker[0].getMonth()+1;
//                        dayOfMonth[0] = datePicker[0].getDayOfMonth();
                        moneyYear=datePicker[0].getYear();
                        moneyMonth=datePicker[0].getMonth();
                        moneyDay=datePicker[0].getDayOfMonth();
                        int month=moneyMonth+1;
                        moneyDate.setText(moneyYear +"年"+ month +"月"+ moneyDay +"日");
                        dialog.cancel();
                    }
                });
                builder.setNegativeButton("取 消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
                builder.create().show();
            }
        });
        //确认添加按钮
        Button enSure_edit=rootView.findViewById(R.id.ensure_edit);
        enSure_edit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(moneyYear==0||moneyContent==null){
                    new androidx.appcompat.app.AlertDialog.Builder(AccountFragment.this.getContext()).setTitle("提示").setMessage("未选择时间或内容或金额！").show();
                }
                else {
                    moneyNum=Double.parseDouble(moneyNumber.getText().toString());
                    Calendar money_date=new GregorianCalendar(moneyYear,moneyMonth,moneyDay);
                    Money money;
                    if(income==true){
                        money = new Money(moneyId, moneyContent, moneyNum, money_date, true, income, moneyNum, 0);
                    }
                    else {
                        money = new Money(moneyId, moneyContent, moneyNum, money_date, true, income, 0, moneyNum);
                    }
                    listTerNer.process(money,position);
                }
            }
        });

        return rootView;
    }

    private void initItems(){
        String[] item_strings={"其他","吃喝玩乐","交通出行","通讯费用","欠债借款",
                "人情礼物","房租水电","医疗费用","社交红包","逛街购物",
                "运动健身","工资薪水","日常用品","聚会聚餐","基金理财",
                "旅行旅游","添加更多"};
        int[] item_images={R.drawable.other_button,R.drawable.eating_button,R.drawable.transportation_button,R.drawable.message_button,R.drawable.debt_button,
                R.drawable.gift_button,R.drawable.rent_button,R.drawable.cure_button,R.drawable.red_packet_button,R.drawable.shopping_button,
                R.drawable.sport_button,R.drawable.salary_button,R.drawable.tissue_button,R.drawable.meeting_button,R.drawable.fund_button,
                R.drawable.travel_button,R.drawable.more_button};
        for(int i=0;i<17;i++){
            CostItem costItem=new CostItem(item_images[i],item_strings[i]);
            costItemList.add(costItem);
        }
    }

    public interface FragmentInteraction {
        void process(Money money,int position);
    }

    private class CostItemAdapter extends ArrayAdapter<CostItem> {
        private int resourceId;

        //适配器的构造函数，把要适配的数据传入这里
        public CostItemAdapter(@NonNull Context context, int resource, @NonNull List<CostItem> objects) {
            super(context, resource, objects);
            resourceId=resource;
        }

        //设置显示的图片和文字
        @NonNull
        @Override
        public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
            CostItem costItem=(CostItem) getItem(position);
            View view;
            CostItemAdapter.ViewHolder viewHolder;
            if(convertView==null){
                view= LayoutInflater.from(getContext()).inflate(resourceId,parent,false);
                viewHolder=new CostItemAdapter.ViewHolder();
                viewHolder.costImage=(ImageView) view.findViewById(R.id.cost_image);
                viewHolder.costName =(TextView) view.findViewById(R.id.cost_image_name);
                view.setTag(viewHolder);    // 将ViewHolder存储在View中
            }else{
                view=convertView;
                viewHolder = (CostItemAdapter.ViewHolder) view.getTag(); // 重新获取ViewHolder
            }
            viewHolder.costImage.setImageResource(costItem.getItem_id());
            viewHolder.costName.setText(costItem.getItem_name());
            return view;
        }
        class ViewHolder{
            ImageView costImage;
            TextView costName;
        }
    }
}